package com.zoolu.net;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Pattern;

public class NetUtil {

	public static boolean isIPAddress(String str) {
		Pattern pattern = Pattern.compile("[0-9.]+");
		return pattern.matcher(str).matches();
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return "127.0.0.1";
	}

	// Modified by huah in 2013-06-27
	public static int getAvailablePort(int port) 
	{
		DatagramSocket s = null;
		int minPort = port;
		int MAXPORT = 65000;
		for (; minPort < MAXPORT; minPort++) 
		{
			try 
			{
				s = new DatagramSocket(minPort, InetAddress.getLocalHost());
				s.close();
				return minPort;
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				continue;
			}
			catch(Error e)
			{
				e.printStackTrace();
				continue;
			}
		}
		
		return port + com.zoolu.tools.Random.nextInt(MAXPORT - port);
	}
	
	// Added by huah in 2014-04-28
	public static int getRandomPort(int min_port) 
	{
		DatagramSocket s = null;
		int port_range = 65535 - min_port;
		if(port_range <= 0)
			port_range = 10;
		int port = min_port; 
		for (int i = 0; i < port_range; i++) 
		{
			try 
			{
				port = min_port + com.zoolu.tools.Random.nextInt(port_range);
				s = new DatagramSocket(port, InetAddress.getLocalHost());
				s.close();
				break;
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				continue;
			}
			catch(Error e)
			{
				e.printStackTrace();
				continue;
			}
		}
		
		return port;
	}
}
